<?php

use luguohuakai\func\Func;
use luguohuakai\ini\Ini;

require '/usr/lib/zabbix/alertscripts/vendor/autoload.php';

$send_to = $argv[1]; // all代表所有人
$subject = $argv[2];
$message = $argv[3];
$type = $argv[4]; // (多个接收者用‘|’分隔) 1:用户ID 2:部门ID 3:tagID

$agent_id = $argv[5];
$corp_id = $argv[6];
$corp_secret = $argv[7];

$access_token = '';
$ini = Ini::load('/usr/lib/zabbix/alertscripts/wechat.ini');
$expires_time = $ini->get('wechat_expires_time');
if ($expires_time && $expires_time > time()) $access_token = $ini->get('wechat_access_token');
if (!$access_token) {
    $url1 = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corp_id&corpsecret=$corp_secret";
    $rs = Func::get($url1);
    if ($rs) {
        $res = json_decode($rs);
        if ($res) {
            if (isset($res->errcode) && $res->errcode == 0) {
                $access_token = $res->access_token;
                $ini->setAll(['wechat_expires_time' => $res->expires_in + time(), 'wechat_access_token' => $access_token]);
            } else {
                L("request error: $res->errcode $res->errmsg");
            }
        } else {
            L('json_decode error: ' . print_r($rs, true));
        }
    } else {
        L('request wechat server error: ' . $url1);
    }
}

if ($access_token) {
    $url2 = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token";
    $post_data['msgtype'] = 'markdown';
    $post_data['agentid'] = $agent_id;
    $post_data['markdown']['content'] = $subject . "\n" . str_replace('@{ALERT.SENDTO}', "@$send_to", $message);

    $post_data['enable_duplicate_check'] = 1;
    $post_data['duplicate_check_interval'] = 1800;
    if ($type == 1) $post_data['touser'] = '@' . $send_to;
    if ($type == 2) $post_data['toparty'] = $send_to;
    if ($type == 3) $post_data['totag'] = $send_to;
    $result = Func::post($url2, $post_data, [], 2);

    if ($result) {
        $res2 = json_decode($result);
        if ($res2 && $res2->errcode == 0) {
            L('发送成功: ' . $subject, 'info');
        } else {
            L("发送失败: $res2->errcode : $res2->errmsg");
        }
    } else {
        L('request error: ' . $url2);
    }
} else {
    L('access_token not exists.');
}

function L($data, $level = 'error')
{
    Func::logs('zbx', $data, 'human-readable', FILE_APPEND, 'month', $level);
}